﻿using DomainService.IService;
using Infrastructure;
using Infrastructure.IRepository;
using Infrastructure.Repository;
using Microsoft.SqlServer.Server;
using Model;
using Model.BusinessModel;
using Model.BusinessModel.InPut;
using Model.BusinessModel.OutPut;
using Model.DomainModel;
using Model.Form;
using Model.OverallAtuhModel;
using Utility;
using Utility.Enum;

namespace DomainService.Service
{
    /// <summary>
    /// 表单服务实现
    /// </summary>
    public class FormService : IFormService
    {
        #region 构造实例化

        /// <summary>
        /// 表单仓储接口
        /// </summary>
        private readonly IFormRepository _formRepository;

        /// <summary>
        /// 流程仓储接口
        /// </summary>
        private readonly IFlowRepository _flowRepository;

        private readonly IBaseService _baseService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="formRepository"></param>
        /// <param name="baseService"></param>
        /// <param name="flowRepository"></param>
        public FormService(IFormRepository formRepository, IBaseService baseService, IFlowRepository flowRepository)
        {
            _formRepository = formRepository;
            _baseService = baseService;
            _flowRepository = flowRepository;
        }

        #endregion

        #region 接口实现

        /// <summary>
        /// 新增表单信息
        /// </summary>
        /// <param name="examineForm">实体模型</param>
        /// <returns></returns>
        public ReceiveStatus Insert(Form examineForm)
        {
            ReceiveStatus receiveStatus = new();
            examineForm.FormId = Guid.NewGuid().ToString();
            var formModel = _formRepository.GetFormByFormName(examineForm.FormName);
            if (formModel != null && examineForm.FormId != formModel.FormId)
                return ExceptionHelper.CustomException(string.Format("表单名称【{0}】重复，请重新填写!", examineForm.FormName));

            var formFieldModel = JsonHelper.JsonStrToEntity<List<FormFieldModel>>(examineForm.FormData);
            examineForm.FormData = JsonHelper.SerializeObjToJson(formFieldModel);
            _formRepository.Insert(examineForm, BaseSqlRepository.form_insertSql);
            return receiveStatus;
        }

        /// <summary>
        /// 更新表单信息
        /// </summary>
        /// <param name="examineForm"></param>
        /// <returns></returns>
        public ReceiveStatus Update(Form examineForm)
        {
            ReceiveStatus receiveStatus = new();
            var model = _formRepository.GetByKey(examineForm.FormId, BaseSqlRepository.form_selectByKeySql);
            if (model == null)
                return ExceptionHelper.CustomException("该表单不存在，更新失败！");

            var formModel = _formRepository.GetFormByFormName(examineForm.FormName);
            if (formModel != null && examineForm.FormId != formModel.FormId)
                return ExceptionHelper.CustomException(string.Format("表单名称【{0}】重复，请重新填写!", examineForm.FormName));

            var formFieldModel = JsonHelper.JsonStrToEntity<List<FormFieldModel>>(examineForm.FormData);
            examineForm.FormData = JsonHelper.SerializeObjToJson(formFieldModel);
            examineForm.CreateTime = model?.CreateTime ?? examineForm.CreateTime;
            examineForm.CreateUserKey = model?.CreateUserKey ?? examineForm.CreateUserKey;
            _formRepository.Update(examineForm, BaseSqlRepository.form_updateSql);
            return receiveStatus;
        }

        /// <summary>
        /// 获取所有表单
        /// </summary>
        /// <param name="pageResultModel"></param>
        /// <returns></returns>
        public PageResultModel<FormOutPut> GetAllForm(PageResultModel pageResultModel)
        {
            pageResultModel.tableField = " ef.* ";
            pageResultModel.tableName = @" Form as ef  ";
            pageResultModel.orderByField = " ef.CreateTime ";
            pageResultModel.sortType = " desc ";

            //数据权限
            var menuId = _baseService.GetCurrentMenuId();
            var authWhere = _flowRepository.GetDataAuthWhere(menuId, "ef", RuleTypeEnum.DataRowRule);
            pageResultModel.selectWhere = authWhere;

            var list = _formRepository.GetPageList<FormOutPut>(pageResultModel);

            var userList = MemoryCacheHelper.GetCachedDataByKey<List<SysUser>>(ConstHelper.UserCacheKey);
            var depList = MemoryCacheHelper.GetCachedDataByKey<List<SysDepartment>>(ConstHelper.DepartmentCacheKey);
            foreach (var item in list.data)
            {
                item.CreateUserName = userList.data?.Find(f => f.UserId == item.CreateUserKey)?.UserName ?? string.Empty;
                item.DepartmentName = depList.data?.Find(f => f.Id == item.DepartmentId)?.DepartmentName ?? string.Empty;
            }
            return list;
        }

        /// <summary>
        ///获取所有表单
        /// </summary>
        /// <returns></returns>
        public ReceiveStatus<List<Form>> GetAllFormList()
        {
            ReceiveStatus<List<Form>> receiveStatus = new();
            var list = _formRepository.GetAll(BaseSqlRepository.form_selectAllSql);
            receiveStatus.data = list;
            return receiveStatus;
        }

        /// <summary>
        /// 根据主键获取表单
        /// </summary>
        /// <param name="formId">表单主键</param>
        /// <returns></returns>
        public ReceiveStatus<Form> GetFormByFormId(string formId)
        {
            ReceiveStatus<Form> receiveStatus = new();
            if (string.IsNullOrWhiteSpace(formId))
                return ExceptionHelper<Form>.CustomExceptionData("请选择表单!");
            var model = _formRepository.GetByKey(formId, BaseSqlRepository.form_selectByKeySql);
            if (model == null)
                return ExceptionHelper<Form>.CustomExceptionData("表单不存在!");
            receiveStatus.data = model;
            return receiveStatus;
        }

        /// <summary>
        /// 根据表单主键获取字段
        /// </summary>
        /// <param name="formId">表单kye</param>
        /// <returns>返回表单字段</returns>
        public ReceiveStatus<List<SelectOutPut>> GetFormField(string formId)
        {
            ReceiveStatus<List<SelectOutPut>> receiveStatus = new();
            if (string.IsNullOrWhiteSpace(formId))
                return ExceptionHelper<List<SelectOutPut>>.CustomExceptionData("请选择表单!");
            var model = _formRepository.GetByKey(formId, BaseSqlRepository.form_selectByKeySql);
            if (model == null)
                return ExceptionHelper<List<SelectOutPut>>.CustomExceptionData("表单不存在!");

            var formFieldModel = JsonHelper.JsonStrToEntity<List<FormFieldModel>>(model.FormData);
            if (formFieldModel == null)
                return ExceptionHelper<List<SelectOutPut>>.CustomExceptionData("表单不存在字段!");

            List<SelectOutPut> list = new List<SelectOutPut>();
            foreach (var item in formFieldModel)
            {
                SelectOutPut selectOutPut = new()
                {
                    value = item.field.id,
                    label = item.field.options.label
                };
                list.Add(selectOutPut);
            }
            receiveStatus.data = list;
            return receiveStatus;
        }

        /// <summary>
        /// 根据部门ID,获取表单
        /// </summary>
        /// <param name="departmentId">部门id</param>
        /// <returns></returns>
        public ReceiveStatus<List<TreeOutPut>> GetFormByDepId(string departmentId)
        {
            ReceiveStatus<List<TreeOutPut>> receiveStatus = new();
            var list = _formRepository.GetFormByDepId(departmentId);
            List<TreeOutPut> formList = new List<TreeOutPut>();
            foreach (var item in list.Where(f => f.DataState != DataStateEnum.Delete))
            {
                TreeOutPut treeOutPut = new();
                treeOutPut.key = item.FormId;
                if (item.DataState == DataStateEnum.Stop)
                {
                    treeOutPut.disabled = true;
                    treeOutPut.label = item.FormName + "[已停用]";
                }
                else
                {
                    treeOutPut.label = item.FormName;
                }
                formList.Add(treeOutPut);
            }
            receiveStatus.data = formList;
            return receiveStatus;
        }

        /// <summary>
        /// 更新数据状态
        /// </summary>
        /// <param name="input">输入模型</param>
        /// <returns></returns>
        public ReceiveStatus UpdateFormDataState(UpdateDataStateInput input)
        {
            ReceiveStatus receiveStatus = new();
            if (input.Ids.Count == 0)
                return ExceptionHelper.CustomException("请选择更新数据");
            if (input.DataState == 0)
                return ExceptionHelper.CustomException("请设置数据状态");

            if (input.DataState == DataStateEnum.Delete)
            {
                foreach (var item in input.Ids)
                {
                    var flowList = _flowRepository.GetFlowByFormId(item).Where(f => f.DataState != DataStateEnum.Delete).ToList();
                    if (flowList.Count > 0)
                    {
                        return ExceptionHelper.CustomException("该表单已绑定流程,不能删除");
                    }
                }
            }

            _formRepository.UpdateFormDataState(input);
            return receiveStatus;
        }

        #endregion
    }
}
